<?php

namespace app\api\controller;

use addons\signin\library\Service;
use addons\vip\library\Order;
use addons\vip\model\Record;
use addons\vip\model\Vip as VipModel;
use app\admin\model\banner\Banner;
use app\admin\model\Bookclass;
use app\admin\model\bookjieorder\Bookjieorder;
use app\admin\model\Books;
use app\admin\model\books\Booksjie;
use app\admin\model\card\Cardlog;
use app\admin\model\card\Carduser;
use app\admin\model\content\Content;
use app\admin\model\teacher\Share;
use app\admin\model\teacher\Teacher;
use app\admin\model\versions\Versions;
use app\admin\model\view\Card;
use app\admin\model\vip\Viprecore;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\MoneyLog;
use app\common\model\ScoreLog;
use app\common\model\User;
use fast\Date;
use think\cache\driver\Redis;
use think\Db;
use think\Exception;
use think\Request;
use think\Validate;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     * @param string like 1男2女
     * @param string type 1小说2漫画
     * @param string token token
     */
    public function index()
    {

        $token = $this->auth->getToken();
        $like = $this->request->get('like');
        $type = $this->request->get('type');

        if ($token != '' && $like == 0){
            $uid = $this->getToken($token);
            $userInfo = (new \app\admin\model\User())->find($uid);
            $like = $userInfo['like'];
        }
        if ($like == 2){
            $catid = 4;
        }else{
            $catid = 1;
        }

        if ($type == 1){
            $classModel = 'fa_bookclass';
            $class_id_name = "bookclass_id";
            $class_id_name2 = "bookclass_id";
            $BookModel = 'fa_books';
        }
        if ($type == 2){
            $classModel = 'fa_cartoonclass';
            $class_id_name = "cartoonclass_id";
            $class_id_name2 = "class_id";
            $BookModel = 'fa_cartoon';
        }

        $erList =  Db::table($classModel)->where([$class_id_name=>$catid,'status'=>1])->order('weigh desc')->select();

        $erChar = '';
        foreach ($erList as $key=>$value){
            if ($key == 0){
                $erChar .= $value['id'];
            }else{
                $erChar .= ','.$value['id'];
            }
        }
        //二级分类列表
        $catewhere = "status = 1";
        $catewhere .= " && $class_id_name In (".$erChar.")";
        $cateList = Db::table($classModel)->where($catewhere)->limit(3)->order('weigh desc')->select();


        $data = [];
        $cateList = $cateList->all();

        foreach ($cateList as  $key=>$value){
            $books = Db::table($BookModel)->where([$class_id_name2=>$value['id'],'status'=>1])->limit(6)->order('weigh desc')->select();


            if(!empty($books)){
                $cateList[$key]['books'] = $books;
            }else{
                $cateList[$key]['books'] = [];
            }


        }

        //轮播图列表
        $bannerList = (new Banner())->where('status',1)->order('weigh desc')->select();

        $data = [];
        $data['cateList'] = $cateList;
        $data['bannerList'] = $bannerList;
        $data['like'] = $like;
        $this->success('请求成功',$data);
    }


    /**
     * 首页轮播图
     */
    public function banner()
    {
        //轮播图列表
        $bannerList = (new Banner())->where('status',1)->order('weigh desc')->select();
        $this->success('请求成功',$bannerList);

    }

    /**
     * 首页分类
     */
    public function cate()
    {
        $typeList = (new Bookclass())->where(['status'=>1,'bookclass_id'=>0])->order('weigh desc')->field('id,name')->select();
        $this->success('请求成功',$typeList);

    }



    /**
     * 选择分类
     * @ApiMethod (GET)
     * @param int like 类型  1男2女
     * */
    public function cateList(){
        $like = $this->request->get('like');
        if ($like == 2){
            $catid = 4;
        }else{
            $catid = 1;
        }
        $typeList = (new Bookclass())->getAllList2($catid);
        $this->success('请求成功',$typeList);
    }

    /**
     * 获取用户协议和隐私政策
     * @ApiMethod (GET)
     * @param int type 类型  1隐私政策2用户协议3会员协议
     **/
    public function getContent(){
        $contentList = (new Content())->where('id',$this->request->get('type'))->select();
        $this->success('请求成功',$contentList);
    }

    /**
     * @ApiTitle    (获取观阅任务列表)
     * @ApiMethod   (GET)
     * @ApiReturnParams   (name="name", type="string", required=true,, description="优惠券名称", sample="")
     **/
    public function get_view_card(){
//        $aa  =  new Carduser();
//        $aa->id = 1;
//        $bb = $aa->add();
//        $this->success('请求成功',$bb);

        $cardList = Db::table('fa_view_card')->whereNull('deletetime')->order('weigh')->select();
        $this->success('请求成功',$cardList);
    }

    /**
     * 观阅币兑换观阅包
     * @ApiMethod (GET)
     * @param string card_id 观阅包id
     **/
    public function moneyViewCard(){
        $token = $this->auth->getToken();

        $card_id = $this->request->get('card_id');
        $uid = $this->getToken($token);

        $user_info  = (new \app\admin\model\User())->find($uid);
        $share_info  = (new Share())->where(['user_id'=>$uid])->find();
        $card_info = (new Card())->where('id',$card_id)->find();

        if (empty($card_info)){
            $this->error('观阅包不存在');
        }

        if ($card_info['type'] != 1){
            $this->error('此观阅包领取类型为'.$card_info['type'].'现金购买');

        }

        if ($user_info['money'] < $card_info['need']){
            $this->error('余额不足');
        }

        $Carduser = new Carduser();

        $info = $Carduser
            ->where([
                'card_id'=>$card_id,
                'user_id'=>$uid,
                'status'=>1,
                'card_type'=>1
            ])->count();
        if ($info >= $card_info['nums']){
            $this->error('已到最大持有数量');
        }

        Db::startTrans();
        try {
            $Carduser->user_id = $uid;
            $Carduser->card_id = $card_id;
            $Carduser->card_type = 1;
            $result = $Carduser->add();

            if ($result == 1){

                User::money(-$card_info['need'],$uid,'购买观阅包');

                $share = new Share();
                $share->where(['user_id'=>$uid])->setDec('money', $card_info['need']);
                $share->where(['user_id'=>$uid])->setInc('active_ge', $card_info['active']);
                $share->where(['user_id'=>$uid])->setInc('active_zong', $card_info['active']);

                $this->s_teacher($uid);
                if ($user_info['pid'] > 0){
                    $this->shangjia($uid,$user_info['pid'],1,$card_info['active']);
                }
            }

            Db::commit();
        } catch (\Exception $e) {

            Db::rollback();
        }
        if ($result == 1){
            $this->success('成功',$result);
        }else{
            $this->error($result);
        }
    }
    
    
    
    public function s_teacher($uid){
            $info =  Db::table('fa_share')->where(['user_id'=>$uid])->find();

                $teacher = new Teacher();
                if ($info['teacher_id'] > 0 ){
                    $teacher->id = $info['teacher_id'];
                }

                $teacher->push =  $info['first_children'];
                $teacher->active_zong = $info['active_zong'];
                $teacher->active_qu = $info['active_qu'];
                $teacher->active_ge = $info['active_ge'];
                $teacherInfo = $teacher->shengji();

                if ( $teacherInfo &&  $teacherInfo['id'] != $info['teacher_id']){

                    $share = new Share();
                    $new_data['teacher_id'] = $teacherInfo['id'];
                    $new_data['updatedtime'] = time();

                    $share->where(['id'=>$info['id']])->update($new_data);

                    $Carduser = new Carduser();
                    $card_id = $teacherInfo['card_id'];
                    $carduserinfo = $Carduser->where(['card_type'=>2,'card_id'=>$card_id,'user_id'=>$uid])->find();

                    if (empty($carduserinfo)){
                        $Carduser->user_id = $uid;
                        $Carduser->card_id = $card_id;
                        $Carduser->card_type = 2;
                        $cardUserreslt = $Carduser->add();
                    }

                }                     
    }


    /*
    *处理数据
    */
    public function  chuli(){


        $this->success('成功',$this->request->root(true));



        // 给定的id数组
        $idArray = [6850,6851,6861,6878,6879,6880,6881,6882,6883,6884,6888,6889,6890,6891,6892,6893,6894,6895,6898,6903,6905,6906,6907,6908,6909,6910,6911,6912,6914,6917,6918,6919,6920,6921,6922,6923,6924,6925,6926,6927,6934,6935,6941,6958,6968,6969,6970,6971,6972,6973,6976,6977,6978,6990,7029,7032,7034,7037,7039,7041,7043,7045,7047,7049,7051,7056,7065,7067,7071,7073,7076,7078,7080,7082,7084,7086,7089,7091,7096,7098,7114,7117,7121,7122,7124,7126,7129,7131,7143,7195,7197,7267];
        // $idArray = [6850,6851];
        // 查询view_card_user表中id等于给定数组的所有数据
        $viewCardUserData = Db::name('view_card_user')
            ->whereIn('id', $idArray)
            ->select();

        // 初始化数组来保存结果
        $result = [];

        // 循环数组，使用card_id去view_card表查找need字段
        foreach ($viewCardUserData as $userData) {
            $cardId = $userData['card_id'];

            // 查询view_card表中card_id等于当前循环的值的need字段
            $card_info = Db::name('view_card')
                ->where('id', $cardId)
                ->find();

            $str =[387,117,390,93,2212,158,225,1923,2252,1171,386,400];

            if (in_array($userData['user_id'], $str)) {
                $uid = $userData['user_id'];

                $userinfo = (new User())->find($uid);

                if ($userinfo['money'] < $card_info['need']){
                    $result = Db::name('view_card_user')->where('id', $userData['id'])->delete();
                }else{
                    User::money(-$card_info['need'],$uid,'购买观阅包.');
                    $share = new Share();
                    $share->where(['user_id'=>$uid])->setDec('money', $card_info['need']);
                    $user_info  = (new \app\admin\model\User())->find($uid);

                    if ($user_info['pid'] > 0){
                        $this->shangjia($uid,$user_info['pid'],1,$card_info['active']);
                    }
                }


            }
        }
        $this->success('成功',$result);
    }


    /*
   * 为上级减掉活跃值
   */
    public function shangjia2($uid,$pid,$type,$active)
    {
        if ($pid > 0){
            Db::table('fa_share')->where(['user_id'=>$pid])->setDec('active_zong', $active);
            $big = $this->big($pid);
            if ($big > 0){
                $userIds = (new \app\admin\model\User())->where(['pid'=>$pid])->where('id', '<>', $big)->column('id');
                if (!empty($userIds)){
                    $totalActiveZong = Db::name('share')
                        ->where('user_id', 'in',implode(',',$userIds))
                        ->sum('active_zong');
                    Db::table('fa_share')->where(['user_id'=>$pid])->update(['active_qu' => $totalActiveZong,'text' => implode(',',$userIds)]);
                }
            }
            $user  = (new \app\admin\model\User())->find($pid);

            if($user['pid'] > 0){
                $this->shangjia2($user['id'],$user['pid'],2,$active);
            }
        }
    }



    /*
     * 为上级增加活跃值
     */
    public function shangjia($uid,$pid,$type,$active)
    {
        if ($pid > 0){
            Db::table('fa_share')->where(['user_id'=>$pid])->setInc('active_zong', $active);
            $big = $this->big($pid);
            if ($big > 0){
                $userIds = (new \app\admin\model\User())->where(['pid'=>$pid])->where('id', '<>', $big)->column('id');
                if (!empty($userIds)){
                    $totalActiveZong = Db::name('share')
                        ->where('user_id', 'in',implode(',',$userIds))
                        ->sum('active_zong');
                    Db::table('fa_share')->where(['user_id'=>$pid])->update(['active_qu' => $totalActiveZong,'text' => implode(',',$userIds)]);
                }
            }
            $user  = (new \app\admin\model\User())->find($pid);

            /*升级*/
            //查询上级邀请信息
            $info =  Db::table('fa_share')->where(['user_id'=>$pid])->find();
            if ($info){
                $teacher = new Teacher();
                if ($info['teacher_id'] > 0 ){
                    $teacher->id = $info['teacher_id'];
                }

                $teacher->push =  $info['first_children'];
                $teacher->active_zong = $info['active_zong'];
                $teacher->active_qu = $info['active_qu'];
                $teacher->active_ge = $info['active_ge'];
                $teacherInfo = $teacher->shengji();

                if ( $teacherInfo &&  $teacherInfo['id'] != $info['teacher_id']){

                    $share = new Share();
                    $new_data['teacher_id'] = $teacherInfo['id'];
                    $new_data['updatedtime'] = time();

                    $share->where(['id'=>$info['id']])->update($new_data);

                    $Carduser = new Carduser();
                    $card_id = $teacherInfo['card_id'];
                    $carduserinfo = $Carduser->where(['card_type'=>2,'card_id'=>$card_id,'user_id'=>$pid])->find();

                    if (empty($carduserinfo)){
                        $Carduser->user_id = $pid;
                        $Carduser->card_id = $card_id;
                        $Carduser->card_type = 2;
                        $cardUserreslt = $Carduser->add();
                    }

                }
            }
            /*升级结束*/


            Db::table('fa_share_active')->insert(['user_id'=>$pid,'pid'=>$user['pid'],'active'=>$active,'addtime'=>time()]);
            if($user['pid'] > 0){
                $this->shangjia($user['id'],$user['pid'],2,$active);
            }
        }
    }


    /*
     * 获取大区的用户信息
     */
    public function big($uid)
    {
        $userIds = (new \app\admin\model\User())->where(['pid'=>$uid])->column('id');

        // 判断是否有符合条件的记录
        if (!empty($userIds)) {
            // 用找到的user表中的id去fa_share_active表查找每条记录的active加起来最大的id
            $maxActiveId = Db::name('share')
                ->whereIn('user_id', $userIds)
                ->order('active_zong DESC')
                ->value('user_id');
            // 打印结果
            return $maxActiveId;
        } else {
            // 如果没有符合条件的记录
            return 0;
        }
    }




    /**
     * 现金兑换观阅包下单
     * @ApiMethod (GET)
     * @param string card_id 观阅包id
     * @param string pay 支付场景app,wap
     * @param int appid appid
     * @param int paytype 支付方式 alipay,wechat
     **/
    public function buyViewCard(){
        $token = $this->auth->getToken();
        $card_id = $this->request->get('card_id');
        $appid = $this->request->get('appid');
        $paytype = $this->request->get('paytype');
        $pay = $this->request->get('pay');

        $uid = $this->getToken($token);
        $user_info  = (new \app\admin\model\User())->find($uid);
        $share_info  = (new Share())->where(['user_id'=>$uid])->find();
        $card_info = (new Card())->where('id',$card_id)->find();

        if (empty($card_info)){
            $this->error('观阅包不存在');
        }
        
        
        $Carduser = new Carduser();

        $info = $Carduser
            ->where([
                'card_id'=>$card_id,
                'user_id'=>$uid,
                'status'=>1,
                'card_type'=>1
            ])->count();
        if ($info >= $card_info['nums']){
            $this->error('已到最大持有数量');
        }


        Db::startTrans();
        try {
            $order_data = [
                'user_id' => $uid,
                'card_id' => $card_id,
                'orderid' => time().$uid,
                'method' => $paytype,
                'addtime' => time(),
            ];

            $order_info = Db::table('fa_view_card_order')->insertGetId($order_data);
            // $notifyurl = $this->request->root(true) . '/addons/epay/api/cardnotifyx/type/' . $paytype;
            // $returnurl = $this->request->root(true) . '/addons/epay/index/returnx/paytype/' . $paytype ;
            // $response = Order::cardsubmit($card_id, $order_info, $card_info['need'], $paytype, $pay, '', $notifyurl, $returnurl);
            
            
            $notifyurl = $this->request->root(true) . '/addons/epay/api/cardnotifyx/type/' . $paytype;
            // $returnurl = $this->request->root(true) . '/addons/epay/index/returnx/paytype/' . $paytype . '/out_trade_no/' . $out_trade_no;
            $returnurl = 'http://static.hhwyxs.cn/#/';

            $title = '购买体验观阅包';
    
            $response = \addons\epay\library\Service::submitOrder($card_info['need'], $order_info, $paytype, $title, $notifyurl, $returnurl, $pay);
            
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
        
        $data['out_trade_no'] = $order_info;
        $data['url'] = $response;
        $this->success('成功',$data);
    }

    /**
     * 查询是否有任务
     * @ApiMethod (GET)

     **/
    public function getViewCardLog(){
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);



        $list = Db::table('fa_view_card_user')
            ->alias('a')
            ->join('fa_view_card b','a.card_id = b.id','left')
            ->where('a.status','=',1)
            ->where('a.user_id','=',$uid)
            ->where('a.endtime','>',time())
            ->field('a.id,a.card_id,a.user_id,b.day_nums,b.name')
            ->select();

        if (empty($list)){
            $this->success('暂无进行中任务',0);
        }

        // 获取当前日期的 0 点时间戳
        $todayStartTimestamp = strtotime(date('Y-m-d 00:00:00'));
        // 获取当前日期的 24 点时间戳（即第二天的 0 点）
        $todayEndTimestamp = strtotime(date('Y-m-d 00:00:00', strtotime('+1 day')));
        $num = 0;
        foreach ($list as $key=>$value) {
            $info = Db::table('fa_view_card_log')
                ->where('card_id', $value['card_id'])
                ->where('user_id', $value['user_id'])
                ->where('log_id', $value['id'])
                ->where('addtime', '>=', $todayStartTimestamp) // 时间大于等于开始时间戳
                ->where('addtime', '<=', $todayEndTimestamp) // 时间小于等于结束时间戳
                ->find();

            if (empty($info)){
                $num ++ ;
            }
        }

        $this->success('获取成功',$num);

    }


    /**
     *
     * 查询我的任务列表
     * @ApiMethod (GET)
     *
     **/
    public function getViewCardList(){
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);

        $list = Db::table('fa_view_card_user')
            ->alias('a')
            ->join('fa_view_card b','a.card_id = b.id','left')
            ->where('a.status','=',1)
            ->where('a.user_id','=',$uid)
            ->where('a.endtime','>',time())
            ->field('a.*,b.day_nums,b.name,b.nums,need')
            ->select();


        // 获取当前日期的 0 点时间戳
        $todayStartTimestamp = strtotime(date('Y-m-d 00:00:00'));
        // 获取当前日期的 24 点时间戳（即第二天的 0 点）
        $todayEndTimestamp = strtotime(date('Y-m-d 00:00:00', strtotime('+1 day')));
        $list = $list->all();

        foreach ($list as $key=>$value){
            $info = Db::table('fa_view_card_log')
                ->where('card_id',$value['card_id'])
                ->where('user_id',$value['user_id'])
                ->where('log_id',$value['id'])
                ->where('addtime', '>=', $todayStartTimestamp) // 时间大于等于开始时间戳
                ->where('addtime', '<=', $todayEndTimestamp) // 时间小于等于结束时间戳
                ->find();
            if (empty($info)){
                $list[$key]['is_jie'] = 1;
                $list[$key]['log_id'] = 0;
                $list[$key]['log_id'] = 0;
            }else{
                $list[$key]['is_jie'] = 0;
                $list[$key]['log_id'] = $info['id'];
                $list[$key]['ling'] = $info['ling'];
            }
        }


        $this->success('获取成功',$list);

    }


    /**
     * 观看小说获得观阅收益
     * @ApiMethod (GET)
     **/
    public function getViewCardMoney(){
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);

        $list = Db::table('fa_view_card_user')
            ->alias('a')
            ->join('fa_view_card b','a.card_id = b.id','left')
            ->where('a.status','=',1)
            ->where('a.user_id','=',$uid)
            ->where('a.endtime','>',time())
            ->field('a.id,a.card_id,a.user_id,b.day_nums,b.name')
            ->select();

        if (empty($list)){
            $this->success('暂无进行中任务');
        }

        // 获取当前日期的 0 点时间戳
        $todayStartTimestamp = strtotime(date('Y-m-d 00:00:00'));
        // 获取当前日期的 24 点时间戳（即第二天的 0 点）
        $todayEndTimestamp = strtotime(date('Y-m-d 00:00:00', strtotime('+1 day')));
        foreach ($list as $key=>$value){
            $info = Db::table('fa_view_card_log')
                ->where('card_id',$value['card_id'])
                ->where('user_id',$value['user_id'])
                ->where('log_id',$value['id'])
                ->where('addtime', '>=', $todayStartTimestamp) // 时间大于等于开始时间戳
                ->where('addtime', '<=', $todayEndTimestamp) // 时间小于等于结束时间戳
                ->find();
            if (empty($info)){
                $data  = [
                    'user_id' => $value['user_id'],
                    'card_id' => $value['card_id'],
                    'log_id' => $value['id'],
                    'day_nums' => $value['day_nums'],
                    'addtime' => time(),
                ];
                Db::startTrans();
                try {
                    $result = Db::table('fa_view_card_log')->insert($data);
                    Db::table('fa_view_card_user')->where('id',$value['id'])->update(['updatedtime'=>time()]);
                    Db::table('fa_view_card_user')->where('id',$value['id'])->setInc('day_now');
                    Db::table('fa_view_card_user')->where('id',$value['id'])->setDec('day_no');

//                        $result = User::money(+$value['day_nums'],$value['user_id'],$value['name'].'观阅任务获得收益');
//                        $share = new Share();
//                        $share->where(['user_id'=>$uid])->setInc('money', $value['day_nums']);
//                        $share->where(['user_id'=>$uid])->setInc('total_money', $value['day_nums']);

                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                }
            }
        }
        $this->success('成功',1);
    }


    /**
     * 领取完成任务奖励
     * @ApiMethod (POST)
     * @param int id 记录id
     **/
    public function ling()
    {
        $token = $this->auth->getToken();
        $id = $this->request->post('id');
        $uid = $this->getToken($token);
        $logInfo  = Db::table('fa_view_card_log')->find($id);


        if (empty($logInfo)) {
            $this->error('任务不存在');
        }

        if($logInfo['ling'] == 1){
            $this->error('请勿重复领取');
        }

        $info = Db::table('fa_view_card_user')
            ->alias('a')
            ->join('fa_view_card b','a.card_id = b.id','left')
            ->where('a.status','=',1)
            ->where('a.user_id','=',$uid)
            ->where('a.id','=',$logInfo['log_id'])
            ->field('a.id,a.card_id,a.user_id,b.day_nums,b.name')
            ->find();

        Db::startTrans();
        try {

            $user_info  = (new \app\admin\model\User())->find($uid);

            if ($user_info['pid'] > 0) {
                User::money(+$info['day_nums']*0.05,$user_info['pid'],'直推下级'.$user_info['nickname'].'观阅任务获得推广收益');
            }



            User::money(+$info['day_nums'],$info['user_id'],$info['name'].'观阅任务获得收益');
            $share = new Share();

            $infos = $share->where(['user_id'=>$uid])->find();
            if(empty($infos)){
                $share->insert(['user_id'=>$uid,'addtime'=>time()]);
            }

            $share->where(['user_id'=>$uid])->setInc('money', $info['day_nums']);
            $share->where(['user_id'=>$uid])->setInc('total_money', $info['day_nums']);
            $result = Db::table('fa_view_card_log')->where('id',$id)->update(['ling'=>1]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }


        if($result){
            $this->success('成功',$result);
        }

        $this->error('领取失败',$result);

    }




    /**
     * 我的粉丝
     * @ApiMethod (GET)

     **/
    public function myfans(){
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);

        $User = new User();
        $userInfo = $User->field('id,pid,nickname,avatar')->find($uid);
        $userInfo['p_info'] = [];
        $userInfo['fans_list'] = [];

        if ($userInfo['pid'] > 0){
            $userInfo['p_info']  = $User->field('id,pid,nickname,avatar,userId')->find($userInfo['pid']);
            $addtime = Db::table('fa_share_log')->where(['user_id'=>$uid,'pid'=>$userInfo['pid']])->find();
            $userInfo['p_info']['addtime'] = date('Y-m-d H:i:s',$addtime['addtime']);
        }

        $userInfo['fans_list'] = Db::table('fa_share_log')
            ->alias('a')
            ->join('fa_user b','a.user_id = b.id','left')
            ->where('a.pid','=',$uid)
            ->field('a.id,b.avatar,b.nickname,FROM_UNIXTIME(addtime, "%Y/%m/%d %H:%i:%s") as addtime')
            ->order('a.addtime desc')
            ->select();

        $userInfo['fans_count'] = Db::table('fa_share_log')
            ->alias('a')
            ->join('fa_user b','a.user_id = b.id','left')
            ->where('a.pid','=',$uid)
            ->count();

        $fa_share = (new Share())->where(['user_id'=>$uid])->find();
        $userInfo['active'] = $fa_share['active_zong'] - $fa_share['active_qu'];

        $this->success('成功',$userInfo);

    }


    /**
     * 我的书券
     * @ApiMethod (GET)

     **/
    public function mymoney(){
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);

        $User = new User();
        $userInfo = $User->field('id,money')->find($uid);
        $userInfo['money_log'] = (new MoneyLog())->where('user_id',$uid)->field('*,FROM_UNIXTIME(createtime, "%Y/%m/%d %H:%i:%s") as createtime')->order('createtime desc')->select();
         $userInfo['money'] = number_format($userInfo['money'], 2); // 截取小数点后两位

        $this->success('成功',$userInfo);
    }


    /**
     * 我的金币
     * @ApiMethod (GET)

     **/
    public function myscore(){
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);

        $User = new User();
        $userInfo = $User->field('id,score')->find($uid);
        $userInfo['money_log'] = (new ScoreLog())->where('user_id',$uid)->field('*,FROM_UNIXTIME(createtime, "%Y/%m/%d %H:%i:%s") as createtime')->order('createtime desc')->select();

        $this->success('成功',$userInfo);
    }



    /**
     * 充值中心页面
     * @ApiMethod (GET)

     **/
    public function moneyConfig(){
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $User = new User();
        $userInfo = $User->field('id,score,money')->find($uid);
        $userInfo['money_config'] = (new \app\admin\model\money\Money())->where('status',1)->order('weigh desc')->select();
        $site = config('site');
        $score_config['convert'] = $site['convert'];
        $score_config['money'] = $userInfo['money'];
        $score_config['score_get'] = $userInfo['money']*$site['convert'];
        $userInfo['score_config'] = $score_config;

        $this->success('请求成功',$userInfo);
    }


    /**
     * 书券兑换
     * @ApiMethod (GET)
     * @param string money 书券数量
     **/
    public function convert_money(){
        $token = $this->auth->getToken();
        $money = $this->request->get('money');
        $uid = $this->getToken($token);
        $User = new User();
        $userInfo = $User->field('id,score,money')->find($uid);
        $site = config('site');
        $convert = $site['convert'];

        if ($userInfo['money'] < $money){
            $this->error('书券余额不足');
        }

        $socore = $money * $convert;
        Db::startTrans();
        try {
            User::money(-$money,$uid,'兑换金币扣除');
            User::score(+$socore,$uid,'使用书券兑换获得');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
        $this->success('成功');
    }

    /**
     * 兑换比例接口
     * @ApiMethod (GET)
     **/
    public function convert()
    {
        $site = config('site');
        $convert = $site['convert'];
        $this->success('成功',$convert);
    }


    /**
     * 转增书券
     * @ApiMethod (GET)
     * @param string money 书券数量
     * @param string mobile 转赠用户手机号
     **/
    public function givemoney(){
        $token = $this->auth->getToken();
        $this->error('请求失败');
        $money = $this->request->get('money');
        $mobile = $this->request->get('mobile');
        $uid = $this->getToken($token);

        $User = new User();
        $userInfo = $User->field('id,score,money,nickname,pid')->find($uid);
        $userInfo2 = $User->field('id,score,money,nickname')->where('mobile',$mobile)->find();
        $site = config('site');
        $fee = $site['fee'];

        if ($userInfo['money'] < $money){
            $this->error('书券余额不足');
        }


        if ($userInfo['pid'] > 0){
            $share = (new Share())->where(['user_id'=>$userInfo['pid']])->find();
        }

        $givemoney = $money * $fee;
        Db::startTrans();
        try {
            User::money(-$givemoney,$uid,'转增用户'.$userInfo2['nickname'].'扣除');
            User::money(+$givemoney,$userInfo2['id'],'用户'.$userInfo['nickname'].'转增获得');
            Db::commit();

        } catch (\Exception $e) {
            Db::rollback();
        }
        $this->success('成功');
    }



    /**
     * 立即签到
     * @ApiMethod (GET)

     **/
    public function dosign()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);


        $config = get_addon_config('signin');
        $signdata = $config['signinscore'];

        $lastdata = \addons\signin\model\Signin::where('user_id', $uid)->order('createtime', 'desc')->find();
        $successions = $lastdata && $lastdata['createtime'] > Date::unixtime('day', -1) ? $lastdata['successions'] : 0;
        $signin = \addons\signin\model\Signin::where('user_id', $uid)->whereTime('createtime', 'today')->find();
        if ($signin) {
            $this->error('今天已签到,请明天再来!');
        } else {
            $successions++;
            $score = isset($signdata['s' . $successions]) ? $signdata['s' . $successions] : $signdata['sn'];
            Db::startTrans();
            try {
                \addons\signin\model\Signin::create(['user_id' => $uid, 'successions' => $successions, 'createtime' => time()]);
                \app\common\model\User::score($score, $uid, "连续签到{$successions}天");
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error('签到失败,请稍后重试');
            }
            $this->success('签到成功!连续签到' . $successions . '天!获得' . $score . '积分');
        }
    }


    /**
     * 签到信息
     * @ApiMethod (GET)

     **/
    public function sign()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $lastdata = \addons\signin\model\Signin::where('user_id', $uid)->order('createtime', 'desc')->find();

        $config = get_addon_config('signin');
        $signdata = $config['signinscore'];
        $successions = $lastdata && $lastdata['createtime'] > Date::unixtime('day', -1) ? $lastdata['successions'] : 0;
        $successions++;
        $score = isset($signdata['s' . $successions]) ? $signdata['s' . $successions] : $signdata['sn'];
        $lastdata['score'] = $score;

        $this->success('', $lastdata);
    }


    /**
     * cdk兑换列表
     * @ApiMethod (GET)
     **/
    public function cdk()
    {
        $cdklist = Db::table('fa_cdk')->order('weigh asc')->select();
        $this->success('成功',$cdklist);
    }




    /**
     * 设置交易密码
     * @ApiMethod (POST)
     * @param string pay_pass 密码
     * @param string mobile  手机号
     * @param string captcha 验证码
     **/
    public function setpassword()
    {
        $user = $this->auth->getUser();
        $captcha = $this->request->post('captcha');
        $mobile  = $this->request->post('mobile');
        $pay_pass = $this->request->post('pay_pass');

        if (!$captcha) {
            $this->error(__('Invalid parameters'));
        }

        $result = Sms::check($mobile, $captcha, 'resetpwd');
        if (!$result) {
            $this->error(__('验证码错误'));
        }
        $verification = $user->verification;
        $user->verification = $verification;

        $userInfo = $this->auth->getUser();
        $userInfo->pay_pass = $pay_pass;
        $userInfo->save();
        Sms::flush($mobile, 'resetpwd');
        $this->success('设置成功');
    }

    /**
     * 判断是否设置免密支付
     * @ApiMethod (GET)
     **/
    public function getnopassword(){
        $userInfo = $this->auth->getUser();
        if ($userInfo->no_pass == 1){
            $this->success('未设置',$userInfo->no_pass);
        }
        $this->success('已设置',$userInfo->no_pass);
    }


    /**
     * 判断是否设置交易密码
     * @ApiMethod (GET)
     **/
    public function getpassword(){
        $userInfo = $this->auth->getUser();
        if ($userInfo->pay_pass == ''){
            $this->success('未设置',0);
        }
        $this->success('已设置',1);
    }

    /**
     * 判断交易密码是否正确接口
     * @ApiMethod (GET)
     * @param string pay_pass 密码
     **/
    public function truepassword(){
        $pay_pass = $this->request->get('pay_pass');
        $userInfo = $this->auth->getUser();
        if ($userInfo->pay_pass != $pay_pass){
            $this->success('密码错误',0);
        }
        $this->success('密码一致',1);
    }


    public function money_order_status(){
        $orderid = $this->request->get('orderid');
        $userInfo = $this->auth->getUser();


        $info = Db::table('fa_money_order')->where('orderid',$orderid)->find();

        $this->success('获取成功',$info['status']);
    }



    /**
     * 免密支付设置
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     *
     */
    public function setnopass()
    {
        $user = $this->auth->getUser();
        $captcha = $this->request->post('captcha');
        $mobile  = $this->request->post('mobile');
        if (!$captcha) {
            $this->error(__('Invalid parameters'));
        }

        $result = Sms::check($mobile, $captcha, 'notice');
        if (!$result) {
            $this->error(__('验证码错误'));
        }
        $verification = $user->verification;
        $user->verification = $verification;
        if ($user->no_pass == 1){
            $user->no_pass = 2;
        }else{
            $user->no_pass = 1;
        }
        $user->save();

        Sms::flush($mobile, 'notice');
        $this->success('设置成功');
    }

    /**
     * 获取是否实名认证1是0否
     * @ApiMethod (get)
     */
    public function shiming(){
        $user = $this->auth->getUser();
        if ($user->id_card != '' && $user->username != ''  && $user->facePhotoUrl != '' ){
            $this->success('已实名',1);
        }
        $this->success('未实名',0);
    }


    /**
     * 获取实名认证奖励是否领取0=否,1=是
     * @ApiMethod (get)
     */
    public function shiming_score(){
        $user = $this->auth->getUser();
        if ($user->shi_score == 1){
            $this->success('已领取',1);
        }
        $this->success('未领取',0);
    }

    /**
     * 实名认证奖励领取接口
     * @ApiMethod (get)
     */
    public function renzheng_score(){
        $user = $this->auth->getUser();
        if ($user->id_card == '' && $user->username == ''  && $user->facePhotoUrl == '' ){
            $this->error('未实名认证');
        }

        if ($user->shi_score == 1){
            $this->error('请勿重复领取');
        }
        $site = config('site');
        \app\common\model\User::score($site['shiming'], $user->id, "实名认证奖励");

        $user->shi_score = 1;
        $user->save();
        $this->success('领取成功');

    }

    /**
     * 实名认证接口
     * @ApiMethod (POST)
     * @param string $name  姓名
     * @param string $idCardNo 身份证号
     * @param string $facePhotoUrl  人脸照片地址
     */
    public function renzheng(){
        $name = $this->request->post('name');
        $idCardNo = $this->request->post('idCardNo');
        $facePhotoUrl = $this->request->post('facePhotoUrl');
        $user = $this->auth->getUser();


        $count = (new \app\admin\model\User())->where('id','<>',$user['id'])->where(['id_card'=>$idCardNo])->count();
        if ($count >= 1){
            $this->error('该身份证已他人被绑定');
        }
        
        $host = "https://jmfaceid.market.alicloudapi.com";
        $path = "/idcard-face/validate";
        $method = "POST";
        $appcode = "d9eeb720448d4ee485fac21a1dc61755";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/x-www-form-urlencoded; charset=UTF-8");
        $querys = "";
        $bodys = 'facePhotoUrl='.$facePhotoUrl.'&idCardNo='.$idCardNo.'&name='.$name;
        $url = $host . $path;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        //设定返回信息中是否包含响应信息头，启用时会将响应信息头作为数据流输出，true 表示输出信息头, false表示不输出信息头
        //如果想将响应结果json字符串转为json数组，建议将 CURLOPT_HEADER 设置成 false
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $reponse = curl_exec($curl);
        curl_close($curl);
        $res = (array)json_decode($reponse, true);

        if ($res['code']  != 200){
            $this->error($res['msg']);
        }

        $incorrect = $res['data']['incorrect'];

        if ($incorrect != 100){
            $this->error($res['data']['msg']);
        }


        $results = $res['data']['result'];

        if ($results != 1){
            $this->error($res['data']['msg']);
        }

        $user->id_card = $idCardNo;
        $user->username = $name;
        $user->facePhotoUrl = $facePhotoUrl;
        $user->save();
        $this->success('设置成功',$res['data']);
    }


    /**
     * 实名认证接口
     * @ApiMethod (POST)
     * @param string $name  姓名
     * @param string $idCardNo 身份证号
     * @param string $facePhotoUrl  人脸照片地址
     */
    public function renzheng2(){
        $name = $this->request->post('name');
        $idCardNo = $this->request->post('idCardNo');
        $facePhotoUrl = $this->request->post('facePhotoUrl');
        $user = $this->auth->getUser();

        $count = (new \app\admin\model\User())->where('id','<>',$user['id'])->where(['id_card'=>$idCardNo])->count();
        if ($count > 1){
            $this->error('该身份证已他人被绑定');
        }
        
        if($user->id_card != '' && $user->username != '' && $user->facePhotoUrl != ''){
                    $this->success('请勿重复认证');

        }

        if ($user->id_card == '' && $idCardNo != '' && $name != ''){
            $result = $this->shenfenz($idCardNo,$name);

            if ($result['error_code']  != 0){
                $this->error('库中无此号');
            }

            if ($result['result']['isok'] == false){
                $this->error('身份证和姓名不匹配');
            }

            $user->id_card = $idCardNo;
            $user->username = $name;
        }

        if ($user->id_card != '' && $user->username != '' ){
            $idCardNo = $user->id_card;
            $name = $user->username;
        }

        if ($facePhotoUrl != ''){
            $relian = $this->renlian($name,$idCardNo,$facePhotoUrl);
            if ($relian['code']  != 0){
                $this->error($relian['msg']);
            }

            if ($relian['data']['result'] > 1 && $relian['data']['hackScore'] < 700 ){
                $this->error('不能确定是否为同一人');
            }

            $user->facePhotoUrl = $facePhotoUrl;

        }

        $result = $user->save();



        $this->success('设置成功',$result);
    }


    public function shenfenz($cardNo,$realName)
    {
        $host = "https://zidv2.market.alicloudapi.com";
        $path = "/idcheck/Post";
        $method = "POST";
        $appcode = "01dbc16d52064dd4b26710392c530697";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/x-www-form-urlencoded; charset=UTF-8");
        $querys = "";
        $bodys = "cardNo=".$cardNo."&realName=".$realName;
        $url = $host . $path;
        $res = $this->crul($method,$url,$headers,$host,$bodys);
        return $res;

    }

    public function renlian($name,$idCard,$imgUrl)
    {
        $host = "https://sxfacev2.market.alicloudapi.com";
        $path = "/faceidcard/check";
        $method = "POST";
        $appcode = "01dbc16d52064dd4b26710392c530697";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/x-www-form-urlencoded; charset=UTF-8");
        $querys = "";
        $bodys = 'name='.$name.'&idCard='.$idCard.'&imgUrl='.$imgUrl;
        $url = $host . $path;

        $res = $this->crul($method,$url,$headers,$host,$bodys);
        return $res;

    }



    public function crul($method,$url,$headers,$host,$bodys){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        //设定返回信息中是否包含响应信息头，启用时会将响应信息头作为数据流输出，true 表示输出信息头, false表示不输出信息头
        //如果想将响应结果json字符串转为json数组，建议将 CURLOPT_HEADER 设置成 false
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $reponse = curl_exec($curl);
        curl_close($curl);
        $res = (array)json_decode($reponse, true);
        return $res;
    }


    /**
     * 获取最新版本号
     * @ApiMethod (GET)
     */
    public function version(){
        $version = new Versions();
        $data['anzhuo'] = $version->where(['type'=>1,'status'=>1])->order('weigh desc')->find();
        $data['ios'] = $version->where(['type'=>2,'status'=>1])->order('weigh desc')->find();
        $this->success('获取成功',$data);
    }



}
